package com.vanzo.some.test;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;

/**
 * Created by tisen on 2017/10/24.
 */

public class UserDeserializer implements JsonDeserializer<User> {
    @Override
    public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        final JsonObject jsonObject = json.getAsJsonObject();
        String name = jsonObject.get("姓名").getAsString();
        int age = jsonObject.get("年龄").getAsInt();
        int sex = jsonObject.get("性别").getAsInt();
        final JsonArray jsonFriedArray = jsonObject.get("朋友").getAsJsonArray();
        final String[] friends = new String[jsonFriedArray.size()];
        for (int i = 0; i < jsonFriedArray.size(); i++) {
            final JsonElement jsonElement = jsonFriedArray.get(i);
            friends[i] = jsonElement.getAsString();
        }
        final User user = new User();
        user.setName(name);
        user.setAge(age);
        user.setSex(sex);
        user.setFriends(friends);

        return user;
    }
}
